/**
 * Recovery Component Demo Script
 * 
 * This script demonstrates the comprehensive file recovery functionality
 * implemented in the Recovery.vue component.
 */

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import { useRecoveryStore, useHistoryStore } from '../../stores'

// Demo data setup
const setupDemoData = () => {
  console.log('🚀 Setting up Recovery Component Demo Data...')
  
  const historyStore = useHistoryStore()
  const recoveryStore = useRecoveryStore()
  
  // Mock history versions
  historyStore.versions = [
    {
      id: '-10363f99',
      timestamp: Date.now() - 86400000, // 1 day ago
      fileCount: 15,
      hasEntriesFile: true
    },
    {
      id: '-139835d',
      timestamp: Date.now() - 172800000, // 2 days ago
      fileCount: 12,
      hasEntriesFile: true
    },
    {
      id: '-14c7541d',
      timestamp: Date.now() - 259200000, // 3 days ago
      fileCount: 8,
      hasEntriesFile: true
    }
  ]
  
  // Mock some recovery tasks in queue
  recoveryStore.recoveryQueue = [
    {
      versionId: '-10363f99',
      fileId: 'abc123.ts',
      originalPath: 'src/components/UserProfile.vue',
      targetPath: 'src/components/UserProfile.vue'
    },
    {
      versionId: '-139835d',
      fileId: 'def456.ts',
      originalPath: 'src/utils/validation.ts',
      targetPath: 'src/utils/validation-recovered.ts'
    },
    {
      versionId: '-14c7541d',
      fileId: 'ghi789.ts',
      originalPath: 'src/stores/user.ts',
      targetPath: 'src/stores/user-backup.ts'
    }
  ]
  
  // Mock some completed recoveries
  recoveryStore.completedRecoveries = [
    {
      success: true,
      targetPath: 'src/components/Header.vue',
      bytesWritten: 2048
    },
    {
      success: true,
      targetPath: 'src/utils/helpers.ts',
      bytesWritten: 1536
    }
  ]
  
  // Mock some failed recoveries
  recoveryStore.failedRecoveries = [
    {
      success: false,
      targetPath: 'src/components/Footer.vue',
      error: '目标文件已存在且无法覆盖',
      bytesWritten: 0
    }
  ]
  
  // Mock recovery history
  recoveryStore.recoveryHistory = [
    {
      successful: [
        { success: true, targetPath: 'src/App.vue', bytesWritten: 3072 },
        { success: true, targetPath: 'src/main.ts', bytesWritten: 1024 }
      ],
      failed: [
        { success: false, targetPath: 'src/router.ts', error: '权限不足', bytesWritten: 0 }
      ],
      totalCount: 3,
      duration: 2500
    },
    {
      successful: [
        { success: true, targetPath: 'src/stores/app.ts', bytesWritten: 2560 }
      ],
      failed: [],
      totalCount: 1,
      duration: 800
    }
  ]
  
  console.log('✅ Demo data setup complete!')
  return { historyStore, recoveryStore }
}

// Demo scenarios
const demoScenarios = {
  
  // Scenario 1: File Selection and Single Recovery
  async singleFileRecovery(recoveryStore: any) {
    console.log('\n📁 Demo Scenario 1: Single File Recovery')
    console.log('1. User selects a file from history version')
    console.log('2. Sets target path')
    console.log('3. Configures recovery options')
    console.log('4. Performs single file recovery')
    
    const mockTask = {
      versionId: '-10363f99',
      fileId: 'test123.vue',
      originalPath: 'src/components/TestComponent.vue',
      targetPath: 'src/components/TestComponent-recovered.vue'
    }
    
    const mockOptions = {
      overwrite: false,
      createDirectories: true,
      preserveTimestamp: true
    }
    
    console.log('📋 Recovery Task:', mockTask)
    console.log('⚙️ Recovery Options:', mockOptions)
    
    try {
      const result = await recoveryStore.recoverSingle(mockTask, mockOptions)
      console.log('✅ Recovery Result:', result)
    } catch (error) {
      console.log('❌ Recovery Failed:', error)
    }
  },
  
  // Scenario 2: Batch Recovery with Conflicts
  async batchRecoveryWithConflicts(recoveryStore: any) {
    console.log('\n📦 Demo Scenario 2: Batch Recovery with Conflicts')
    console.log('1. Multiple files queued for recovery')
    console.log('2. Preview shows conflicts')
    console.log('3. User resolves conflicts')
    console.log('4. Batch recovery executes')
    
    // Add more tasks to queue
    const additionalTasks = [
      {
        versionId: '-10363f99',
        fileId: 'conflict1.ts',
        originalPath: 'src/utils/api.ts',
        targetPath: 'src/utils/api.ts' // This will conflict
      },
      {
        versionId: '-139835d',
        fileId: 'conflict2.vue',
        originalPath: 'src/views/Dashboard.vue',
        targetPath: 'src/views/Dashboard.vue' // This will also conflict
      }
    ]
    
    additionalTasks.forEach(task => recoveryStore.addToQueue(task))
    
    console.log('📋 Total queued tasks:', recoveryStore.recoveryQueue.length)
    
    // Preview recovery (would show conflicts)
    const preview = await recoveryStore.previewRecovery()
    console.log('🔍 Recovery Preview:', preview)
    
    if (preview && preview.conflicts.length > 0) {
      console.log('⚠️ Conflicts detected:', preview.conflicts.length)
      console.log('Conflicts:', preview.conflicts)
      
      // Simulate conflict resolution
      const resolutions = preview.conflicts.map(conflict => ({
        targetPath: conflict.targetPath,
        action: conflict.existingFile ? 'rename' : 'overwrite',
        newPath: conflict.existingFile ? `${conflict.targetPath}.recovered` : undefined
      }))
      
      console.log('🔧 Conflict Resolutions:', resolutions)
    }
    
    // Execute batch recovery
    const batchOptions = {
      overwrite: false,
      createDirectories: true,
      preserveTimestamp: true,
      continueOnError: true,
      maxConcurrent: 3
    }
    
    try {
      const result = await recoveryStore.recoverBatch(batchOptions)
      console.log('✅ Batch Recovery Result:', result)
    } catch (error) {
      console.log('❌ Batch Recovery Failed:', error)
    }
  },
  
  // Scenario 3: Recovery Progress Tracking
  async recoveryProgressTracking(recoveryStore: any) {
    console.log('\n📊 Demo Scenario 3: Recovery Progress Tracking')
    console.log('1. Start batch recovery')
    console.log('2. Track progress in real-time')
    console.log('3. Show detailed statistics')
    console.log('4. Handle cancellation')
    
    // Simulate progress updates
    const totalTasks = 5
    let completed = 0
    
    console.log('🚀 Starting recovery process...')
    recoveryStore.isRecovering = true
    recoveryStore.totalTasks = totalTasks
    
    const progressInterval = setInterval(() => {
      completed++
      const progress = (completed / totalTasks) * 100
      
      recoveryStore.progress = progress
      recoveryStore.currentTask = {
        originalPath: `src/file${completed}.ts`,
        targetPath: `dest/file${completed}.ts`
      }
      
      console.log(`📈 Progress: ${progress.toFixed(1)}% - Processing: ${recoveryStore.currentTask.originalPath}`)
      
      if (completed >= totalTasks) {
        clearInterval(progressInterval)
        recoveryStore.isRecovering = false
        recoveryStore.progress = 100
        console.log('✅ Recovery process completed!')
      }
    }, 1000)
    
    // Simulate cancellation after 3 seconds
    setTimeout(() => {
      if (recoveryStore.isRecovering) {
        console.log('🛑 User cancelled recovery')
        clearInterval(progressInterval)
        recoveryStore.cancelRecovery()
      }
    }, 3500)
  },
  
  // Scenario 4: Recovery History and Statistics
  async recoveryHistoryDemo(recoveryStore: any) {
    console.log('\n📈 Demo Scenario 4: Recovery History and Statistics')
    console.log('1. View recovery history')
    console.log('2. Analyze success rates')
    console.log('3. Review failed operations')
    console.log('4. Retry failed recoveries')
    
    console.log('📊 Recovery Statistics:')
    console.log(`- Success Rate: ${recoveryStore.successRate.toFixed(1)}%`)
    console.log(`- Completed Recoveries: ${recoveryStore.completedRecoveries.length}`)
    console.log(`- Failed Recoveries: ${recoveryStore.failedRecoveries.length}`)
    console.log(`- Recent History Entries: ${recoveryStore.recentRecoveries.length}`)
    
    console.log('\n📋 Recent Recovery History:')
    recoveryStore.recentRecoveries.forEach((batch: any, index: number) => {
      console.log(`${index + 1}. Batch Recovery:`)
      console.log(`   - Successful: ${batch.successful.length}`)
      console.log(`   - Failed: ${batch.failed.length}`)
      console.log(`   - Duration: ${batch.duration}ms`)
      console.log(`   - Total: ${batch.totalCount}`)
    })
    
    if (recoveryStore.failedRecoveries.length > 0) {
      console.log('\n🔄 Retrying failed recoveries...')
      recoveryStore.retryFailed()
      console.log(`✅ ${recoveryStore.recoveryQueue.length} tasks added back to queue for retry`)
    }
  },
  
  // Scenario 5: Advanced Recovery Options
  async advancedRecoveryOptions(recoveryStore: any) {
    console.log('\n⚙️ Demo Scenario 5: Advanced Recovery Options')
    console.log('1. Configure recovery options')
    console.log('2. Set batch processing limits')
    console.log('3. Handle directory creation')
    console.log('4. Preserve file metadata')
    
    const advancedOptions = {
      overwrite: true,
      createDirectories: true,
      preserveTimestamp: true,
      continueOnError: false, // Stop on first error
      maxConcurrent: 1 // Process one at a time
    }
    
    console.log('⚙️ Advanced Options:', advancedOptions)
    
    // Update store options
    recoveryStore.updateDefaultOptions(advancedOptions)
    recoveryStore.updateBatchOptions(advancedOptions)
    
    console.log('✅ Options updated successfully')
    
    // Demonstrate path suggestions
    const originalPath = 'src/components/UserProfile.vue'
    const pathSuggestions = [
      'src/UserProfile.vue',
      'src/components/UserProfile.vue',
      'src/views/UserProfile.vue',
      'src/utils/UserProfile.vue',
      originalPath
    ]
    
    console.log('\n📁 Path Suggestions for:', originalPath)
    pathSuggestions.forEach((suggestion, index) => {
      console.log(`${index + 1}. ${suggestion}`)
    })
  }
}

// Main demo execution
export const runRecoveryDemo = async () => {
  console.log('🎯 File Recovery Component Demo')
  console.log('=====================================')
  
  const { historyStore, recoveryStore } = setupDemoData()
  
  try {
    // Run all demo scenarios
    await demoScenarios.singleFileRecovery(recoveryStore)
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    await demoScenarios.batchRecoveryWithConflicts(recoveryStore)
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    await demoScenarios.recoveryProgressTracking(recoveryStore)
    await new Promise(resolve => setTimeout(resolve, 5000))
    
    await demoScenarios.recoveryHistoryDemo(recoveryStore)
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    await demoScenarios.advancedRecoveryOptions(recoveryStore)
    
    console.log('\n🎉 Recovery Component Demo Completed!')
    console.log('=====================================')
    
    // Summary
    console.log('\n📋 Demo Summary:')
    console.log('✅ File selection and single recovery')
    console.log('✅ Batch recovery with conflict resolution')
    console.log('✅ Real-time progress tracking')
    console.log('✅ Recovery history and statistics')
    console.log('✅ Advanced recovery options')
    console.log('✅ Path suggestions and validation')
    console.log('✅ Error handling and retry mechanisms')
    
  } catch (error) {
    console.error('❌ Demo failed:', error)
  }
}

// Export for use in tests or standalone execution
export default {
  setupDemoData,
  demoScenarios,
  runRecoveryDemo
}

// Run demo if this file is executed directly
if (import.meta.env.MODE === 'development') {
  console.log('🔧 Development mode detected - Recovery demo available')
  console.log('Run runRecoveryDemo() to start the demonstration')
}